package com.swfee.qinben;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;

import com.swfee.qinben.base.AppBaseActivity;
import com.swfee.qinben.service.AppLogService;
import com.swfee.qinben.session.AppSession;
import com.swfee.qinben.util.CurenActivitUtils;

public class AppStartActivity extends AppBaseActivity {

	private AppLogService appLogService;
	private boolean firstApp = false;

	private long MAX_WAIT = 1000;// 半秒钟

	private boolean closeFlag = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.app_start);
		// 应用程序是否初始化：
		AppSession.init();
		new Thread(appStartInit).start();
		appLogService = new AppLogService(this);

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 如果是返回键,直接返回到桌面

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			closeFlag = true;
		}
		return super.onKeyDown(keyCode, event);
	}

	Runnable appStartInit = new Runnable() {

		@Override
		public void run() {
			long cluStart = System.currentTimeMillis();

			try {

				firstApp = appLogService.firstUse();
				if(firstApp){
					handler.sendEmptyMessage(1);
					return ;
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log.d("thistag", "首次检测异常。。");
			}

		
			long end = System.currentTimeMillis();
			long cluSum = end - cluStart;
			if (cluSum <= MAX_WAIT) {
				try {
					Thread.sleep(MAX_WAIT - cluSum);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			handler.sendEmptyMessage(0);
		}
	};

	/*
	 * 使用Handler更新UI
	 */
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			if (closeFlag) {
				finish();
				return;
			}
			//first install 第一次安装 
			if(firstApp){
				Log.d("firstApp", firstApp+"");
				CurenActivitUtils.startActivity(AppInstallFirstActivity.class, true);
				return ;
			}
			//到登录页面
			CurenActivitUtils.startActivity(AppLoginActivity.class, true);

		}
	};

}
